/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * <p>Project: smvc2022 - JwtDemo
 * <p>Powered by webrx On 2022-04-07 11:59:19
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class JwtDemo {
    public static void main(String[] args) {
        //生成令牌token
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,30);
        String token = JWT.create()
                //.withHeader(map)//添加头部
                .withClaim("userid","admina")//添加payload
                .withClaim("username","李四")
                .withClaim("email","webrx@126.com")
                .withExpiresAt(instance.getTime())//设置过期时间30分钟后过期
                .sign(Algorithm.HMAC256("webrx"));//设置签名 密钥
        System.out.println(token);

        String t1 = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDkzMDcwOTAsInVzZXJpZCI6ImFkbWluIiwiZW1haWwiOiJ3ZWJyeEAxMjYuY29tIiwidXNlcm5hbWUiOiLmnY7lm5sifQ.4ck_cAtA9BeEUk_iZfV5-UI5HTwxNmxwSVxebsE_2Mk";
        System.out.println(t1.length());
        String t2 = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDkzMDcxMjYsInVzZXJpZCI6ImFkbWluYSIsImVtYWlsIjoid2VicnhAMTI2LmNvbSIsInVzZXJuYW1lIjoi5p2O5ZubIn0.RBU0kRXh_c0Rwk8ec8LxDfgympCguEl6zTM6TWjfpHs";
        System.out.println(t2.length());
        //校验令牌
        JWTVerifier v = JWT.require(Algorithm.HMAC256("webrx")).build();
        String tt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDkzMDcxMjYsInVzZXJpZCI6ImFkbWluYSIsImVtYWlsIjoid2VicnhAMTI2LmNvbSIsInVzZXJuYW1lIjoi5p2O5ZubIn0.4ck_cAtA9BeEUk_iZfV5-UI5HTwxNmxwSVxebsE_2Mk";
        System.out.println(tt.length());
        try{
            DecodedJWT f = v.verify(t1);
            System.out.println(f.getClaim("userid").asString());
            System.out.println(f.getClaim("username").asString());
            System.out.printf("%tF %<tT%n",f.getClaim("exp").asDate());
            System.out.println(f.getPayload());
            System.out.println("-----------------------------------");
            f.getClaims().forEach((key,value)->{
                System.out.println(key);
                System.out.println(value.asString());
            });
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}
